import {Component, OnInit, ViewChild} from '@angular/core';
import {basicSetup, EditorView} from '@codemirror/basic-setup';
import {EditorState, Compartment} from '@codemirror/state'
import {tags, HighlightStyle} from '@codemirror/highlight'
import {Text} from '@codemirror/text'
import {sql} from '@codemirror/lang-sql'

@Component({
    selector: 'app-codemirror6',
    templateUrl: './codemirror6.component.html',
    styleUrls: ['./codemirror6.component.less']
})
export class Codemirror6Component implements OnInit {

    @ViewChild('codeMirrorDev', {static: true})
    parent

    state: EditorState
    view: EditorView

    constructor() {
    }

    ngOnInit(): void {
        const language = new Compartment()
        const tabSize = new Compartment()

        // 设置编辑器样式
        const myTheme = EditorView.theme({
            '&': {
                color: 'white',
                backgroundColor: '#034'
            },
            '.cm-content': {
                caretColor: '#0e9',
                minHeight: '500px'
            },
            '&.cm-focused .cm-cursor': {
                borderLeftColor: '#0e9'
            },
            '&.cm-focused .cm-selectionBackground, ::selection': {
                backgroundColor: '#074'
            },
            '.cm-gutters': {
                backgroundColor: '#045',
                color: '#ddd',
                border: 'none'
            },
            '&.cm-editor': {
                minHeight: '100%'
            }
        }, {dark: true})

        // 设置高亮样式
        const myHighlightStyle = HighlightStyle.define([
            {tag: tags.keyword, color: '#fc6'},
            {tag: tags.comment, color: '#f5d', fontStyle: 'italic'}
        ])

        // 设置编辑器的基本属性
        this.state = EditorState.create({
            extensions: [
                basicSetup,
                language.of(sql()),
                tabSize.of(EditorState.tabSize.of(8)),
                myTheme,
                myHighlightStyle
            ]
        })

        // 初始化
        this.view = new EditorView({
            state: this.state,
            parent: this.parent.nativeElement
        })

        // 设置值
        const tr = this.view.state.update({changes:[{from:0,insert:'select * from oam_operation_apply;'}]})
        this.view.dispatch(tr)
    }

    getValue() {
        // 获取当前内容
        const oriText = this.view.state.doc.toString();
        console.log(oriText)

        const newText = oriText + '\n' + oriText;
        // 设置值
        const tr = this.view.state.update({changes: [{from: 0, insert: newText}]});
        this.view.dispatch(tr);
    }

}
